/*!
 @header OrderDetailViewController.m
 @author 王 文彬
 @version 1.0.0 2013/02/06 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "OrderDetailViewController.h"
#import "Config.h"
#import "Helper.h"
#import "JSONRequest.h"
#import "OrderListViewController.h"
#import "ConfirmPayViewController.h"
#import "DynamicDetailViewController.h"
#import "PersonalViewController.h"
#import "JMFBase.h"
#import "HPopupView.h"

//  -----------------------类详细介绍-----------------------
//  在tableview中，第3、6行是可以被点击的。点击第3行是到商品的商品动态详情页面，点击第6行是卖家或者买家的个人页面。
//
//  订单显示时会根据用户在当前订单所担任的角色不同，而显示的栏目也不同。如果用户是卖家那么在tableview的第6行应该显示卖家，并且在待付款订单、待收货订单
//  历史成功订单中是没有后续操作的，则将后续操作的按钮隐藏，否则显示买家。
//  
//
//  此VC重点在于判断各个订单的状态
//
//  <功能描述>：根据服务器返回来的订单对象的status判断订单类型。不同的订单类型有不同的时间逻辑、title和后续操作
//  一共6种订单，在订单详情中，各类订单的后续操作都不一样。
//  待付款订单显示购买时间，后续操作是去付款操作；待发货订单显示购买时间，后续操作是确认发货操作；待收货订单显示发货时间，后续操作是待确认收货操作；
//  历史成功订单显示收货时间，后续操作是评论；待退款订单和待退货订单显示申请时间，后续操作是查看申请。
//
//      <注意事项>：当为待付款订单时，要判断商品是否下架。
//
//  <功能描述>：后续操作的逻辑。
//      点击待付款订单的付款按钮，会跳转到该订单的确认付款页面；
//      点击待发货订单的确认发货按钮，会弹出一个alertview，提示用户是否要继续此操作；
//      点击待收货订单的确认收获按钮，同待发货订单的确认发货按钮；
//      点击历史成功订单的评论按钮，会跳转到该订单商品的动态详情里面；
//      点击待退款订单的查看申请按钮，会弹出一个alertview，提示用户是否要继续此操作；alertview上3个按钮，拒绝退款、确认退款和暂不处理；
//      点击待退货订单的查看申请按钮，会弹出一个alertview，提示用户是否要继续此操作；alertview上3个按钮，拒绝退货、确认退货和暂不处理；
// 
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述              版本
//
// <#修改人#> <#修改时间#>    <#修改描述#>          <#版本#>


@interface OrderDetailViewController ()

@end

@implementation OrderDetailViewController

@synthesize dismissModal = _dismissModal;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (id)initWithOrderID:(NSInteger)orderID
{
    self = [super init];
    if (self) {
        _orderID = orderID;
    }
    return self;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];

    
    UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    scrollView.contentSize = CGSizeMake(320, 475);
    scrollView.backgroundColor = [UIColor whiteColor];
    self.view = scrollView;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];

    //白色view，用于遮住_tableView的最后一个cell的横线
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, _tableView.frame.size.height - 1, _SYS_FRAME_WIDTH, 1)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    
    //按钮
    _button = [[UIButton alloc] initWithFrame:CGRectMake(10, _tableView.frame.size.height, 300, 40)];
    [_button setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_006_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    _button.hidden = true;
    [self.view addSubview:_button];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //_totalHeight必须在每次视图载入时清零
    _totalHeight = 0;
    
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ORDER_DETAILINFO];
    request.delegate = (id)self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    [request setValue:[NSNumber numberWithInteger:_orderID] forParameter:@"productOrderId"];
    [request asynchronous];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _rowsTitleSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    ///////////////////////
    //下面的注释分为两个部分，一个部分是注释了UILabel，使用了UITextView替换
    //另一个部分是注释了if语句，取消了cell高度按indexPath来判断的语句。现在是让每个cell的高度都计算
    //这些注释在测试通过，稳定版本后，可以移除
    ///////////////////////
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.backgroundColor = [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellEditingStyleNone;
        
        //title文字
        UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 7.5, 80, 20)];
        titleLabel.font = _SYS_FONT_003;
        [cell.contentView addSubview:titleLabel];

        //值
//        UILabel* contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 7.5, 200, 20)];
//        contentLabel.font = _SYS_FONT_003;
//        contentLabel.textColor = _SYS_COLOR_002;
//        contentLabel.numberOfLines = 0;
//        [cell.contentView addSubview:contentLabel];
        
        UITextView* textView = [[UITextView alloc] initWithFrame:CGRectMake(90, 5, 200, 25)];
        textView.font = _SYS_FONT_003;
        textView.textColor = _SYS_COLOR_002;
        textView.scrollEnabled = false;
        textView.editable = false;
        [cell.contentView addSubview:textView];
    }
    
    ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).text = _rowsTitleSource[indexPath.row];
//    ((UILabel *)[cell.contentView.subviews objectAtIndex:1]).text = _rowsDataSource[indexPath.row];
    ((UITextView *)[cell.contentView.subviews objectAtIndex:1]).text = _rowsDataSource[indexPath.row];
    
//    if (indexPath.row == 1) {
//        ((UILabel *)[cell.contentView.subviews objectAtIndex:1]).frame = CGRectMake(90, 7.5, 200, 35);
//        ((UITextView *)[cell.contentView.subviews objectAtIndex:1]).frame = CGRectMake(90, 0, 200, 40);
//    }
//    else if (indexPath.row == 8 || indexPath.row == 10) {
        CGSize size = [_rowsDataSource[indexPath.row] sizeWithFont:_SYS_FONT_003 constrainedToSize:CGSizeMake(200, 200) lineBreakMode:UILineBreakModeWordWrap];
        
//        ((UILabel *)[cell.contentView.subviews objectAtIndex:1]).frame = CGRectMake(90, 7.5, 200, size.height);
        ((UITextView *)[cell.contentView.subviews objectAtIndex:1]).frame = CGRectMake(90, 0, 200, size.height + 20);
//    }
//    else if(indexPath.row == 10) {
//        
//        ((UILabel *)[cell.contentView.subviews objectAtIndex:1]).frame = CGRectMake(90, 7.5, 200, 75);
//    }

    if (indexPath.row ==  2 || indexPath.row == _rowsTitleSource.count - 6) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        ((UITextView *)[cell.contentView.subviews objectAtIndex:1]).userInteractionEnabled = false;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
        ((UITextView *)[cell.contentView.subviews objectAtIndex:1]).userInteractionEnabled = true;
    }
    
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row ==  2) {
        DynamicDetailViewController* dynamicDetailViewController = [[DynamicDetailViewController alloc] initWithID:[_order[@"dynamicId"] integerValue]];
        [self.navigationController pushViewController:dynamicDetailViewController animated:true];
    }
    
    if (indexPath.row == _rowsTitleSource.count - 6) {
        NSInteger xerID;
        if ([_order[@"sellerId"] integerValue] == [_ACCOUNT_ID integerValue]) {
            xerID = [_order[@"buyerId"] integerValue];
        }
        else {
            xerID = [_order[@"sellerId"] integerValue];
        }

        PersonalInfoViewController* personInfoViewController = [[PersonalInfoViewController alloc] initWithPersonId: xerID];
        [self.navigationController pushViewController:personInfoViewController animated:true];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height = 35;
    if (indexPath.row == 1) {
        height = 45;
    }
    else if (indexPath.row == _rowsTitleSource.count - 1 || indexPath.row == _rowsTitleSource.count - 3) {
        CGSize size = [_rowsDataSource[indexPath.row] sizeWithFont:_SYS_FONT_003 constrainedToSize:CGSizeMake(200, 200) lineBreakMode:UILineBreakModeWordWrap];
        
        height = size.height + 25.0f;
    }
    
    if (height < 35) {
        height = 35;
    }
    
    _totalHeight += height;
    return height;
}

#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent
{
    if (_dismissModal) {

        [self.navigationController dismissModalViewControllerAnimated:true];
    }
    else {

        [self.navigationController popViewControllerAnimated:true];
    }
}

///*!
// @abstract 商品名称事件
// */
//- (void)productButtonEvent
//{
//    DynamicDetailViewController* trendDetailVC = [[DynamicDetailViewController alloc] initWithID:[[_order valueForKey:@"dynamicID"] intValue]];
//    [self.navigationController pushViewController:trendDetailVC animated:true];
//}
//
//- (void)nameButtonEvent
//{
//    int personID;
//    
//    if ([[_order objectForKey:@"sellerID"] integerValue] == [_ACCOUNT_ID integerValue]) {
//        personID = [[_order valueForKey:@"buyerID"] integerValue];
//    }
//    else {
//        personID = [[_order valueForKey:@"sellerID"] integerValue];
//    }
//    
//    PersonalInfoViewController* personInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:personID];
//    personInfoVC.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:personInfoVC animated:true];
//}

/*!
 @abstract 所有订单后续操作的按钮事件
 */
- (void)buttonEvent:(id)sender
{

    //快递上门
    if ([[_order valueForKey:@"status"] intValue] == OrderListTypeWillDelivery && [[_order valueForKey:@"deliveryMode"] intValue] == 1) {
        
        UITextField* companyTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, 95, 230, 25)];
        companyTextField.placeholder = _L(@"holder_32");
        companyTextField.font = [UIFont boldSystemFontOfSize:15];
        companyTextField.layer.cornerRadius = 4;
        companyTextField.layer.masksToBounds = YES;
        companyTextField.backgroundColor = UIColor.whiteColor;
        companyTextField.text = _company;
        companyTextField.tag = 100;
        companyTextField.delegate = (id)self;
        companyTextField.borderStyle = UITextBorderStyleRoundedRect;
        [companyTextField becomeFirstResponder];
        
        UITextField* noTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, 127, 230, 25)];
        noTextField.placeholder = _L(@"holder_33");
        noTextField.font = [UIFont boldSystemFontOfSize:15];
        noTextField.layer.cornerRadius = 6;
        noTextField.layer.masksToBounds = YES;
        noTextField.backgroundColor = UIColor.whiteColor;
        noTextField.text = _no;
        noTextField.tag = 101;
        noTextField.delegate = (id)self;
        noTextField.borderStyle = UITextBorderStyleRoundedRect;
        
        HPopupView* popupView = [[HPopupView alloc] initWithFrame:CGRectMake(30, 40, 260, 200)];
        popupView.cancelButtonTitle = _L(@"btn_no_01");
        [popupView addButtonTitlt:_L(@"btn_yes_01")];
        popupView.titleText = _L(@"title_79");
        popupView.contentText = _L(@"alert_76");
        
        [popupView setWillShowBlock:^(UIView *view) {
            
            [view addSubview:companyTextField];
            [view addSubview:noTextField];
        }];
        
        [popupView show];
        
        [popupView setButtonClickedBlock:^BOOL(UIView *view, NSInteger buttonIndex) {

            if (buttonIndex == 0) {
                
                return true;
            }
            
            _no = noTextField.text;
            _company = companyTextField.text;
            NSString* alert;
            if (_no.length > 0) {
                if (_no.length < 2) {
                    alert = _L(@"alert_81");
                }
                else if (_no.length > 50) {
                    alert = _L(@"alert_82");
                }
            }
            if (_company.length > 0 && _no.length == 0) {
                alert = _L(@"alert_78");
            }
            
            if (_company.length > 0) {
                if (_company.length < 2) {
                    alert = _L(@"alert_79");
                }
                else if (_company.length > 50) {
                    alert = _L(@"alert_80");
                }
            }
            if (_company.length == 0 && _no.length > 0) {
                alert = _L(@"alert_77");
            }
            
            if (alert) {
                
                [Helper showAlertWithTitle:nil andMessage:alert];
                return false;
            }
            
            JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ORDER_CONDIGNMENT];
            [request setValue:_company forParameter:@"logisticsCompany"];
            [request setValue:_no forParameter:@"logisticsNumber"];
            request.delegate = (id)self;
            request.hudOn = true;
            request.hudTitle = _L(@"title_loading_01");
            [request setSuccessSelector:@selector(requestSuccessSelector:)];
            [request setValue:_order[@"id"] forParameter:@"productOrderId"];
            [request asynchronous];
            
            _company = @"";
            _no = @"";
            
            return true;
        }];

    }
    else if ([[_order valueForKey:@"status"] intValue] == OrderStatusWillDelivery) {

        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_06") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        [alertView show];
    }
    else if ([[_order valueForKey:@"status"] intValue] == OrderStatusWaitingForConfirm) {
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_07") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        [alertView show];
    }
    else if ([[_order valueForKey:@"status"] intValue] == OrderStatusConfirmed || [[_order valueForKey:@"status"] intValue] == OrderStatusCommented) {

        DynamicDetailViewController* dynamicDetailViewController = [[DynamicDetailViewController alloc] initWithID:[[_order valueForKey:@"dynamicId"] intValue]];
        dynamicDetailViewController.disMode = true;
        dynamicDetailViewController.delegate = self;
        dynamicDetailViewController.orderId = _orderID;

        UINavigationController* messageFormNavigationController = [[UINavigationController alloc] initWithRootViewController:dynamicDetailViewController];
        [Helper navigationControllerCommonStyle:messageFormNavigationController];
        
        [self.navigationController presentModalViewController:messageFormNavigationController animated:true];
    }
    else if ([[_order valueForKey:@"status"] intValue] == OrderStatusWaitingForPay) {
        ConfirmPayViewController* payViewController = [[ConfirmPayViewController alloc] initWithOrder:_order];
        payViewController.dismissModal = true;
        payViewController.delegate = self;

        UINavigationController* messageFormNavigationController = [[UINavigationController alloc] initWithRootViewController:payViewController];
        [Helper navigationControllerCommonStyle:messageFormNavigationController];
        
        [self.navigationController presentModalViewController:messageFormNavigationController animated:true];
    }
    else if ([[_order valueForKey:@"status"] intValue] == 11) {

        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:_order[@"refundReason"] message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:_L(@"btn_refund_01"), _L(@"btn_refund_02"), _L(@"btn_refund_03"), nil];
        alertView.cancelButtonIndex = 2;
        [alertView show];
    }
    else if ([[_order valueForKey:@"status"] intValue] == 13) {
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:_order[@"returnReason"] message:_L(@"alert_08") delegate:self cancelButtonTitle:nil otherButtonTitles:_L(@"btn_return_01"), _L(@"btn_return_02"), _L(@"btn_return_03"), nil];
        alertView.cancelButtonIndex = 2;
        [alertView show];
    }
}


#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ((([_order[@"status"] intValue] == OrderStatusWillDelivery || [_order[@"status"] intValue] == OrderStatusWaitingForConfirm) && buttonIndex == 0 && alertView.tag != 901) ||
        (([_order[@"status"] intValue] == 11 || [_order[@"status"] intValue] == 13) && buttonIndex == 2)) {
        return;
    }

    //确认收货后的询问是否去评论的alertview，且点击了去评论按钮
    if (alertView.tag == 901) {

        if (buttonIndex == 1) {
            
            DynamicDetailViewController* dynamicDetailViewController = [[DynamicDetailViewController alloc] initWithID:[_order[@"dynamicId"] intValue]];
            dynamicDetailViewController.disMode = true;
            dynamicDetailViewController.orderId = [_order[@"id"] intValue];
            
            UINavigationController* messageFormNavigationController = [[UINavigationController alloc] initWithRootViewController:dynamicDetailViewController];
            [Helper navigationControllerCommonStyle:messageFormNavigationController];
            
            [self.navigationController presentModalViewController:messageFormNavigationController animated:true];
        }
        else {
            [self backButtonEvent];
        }

        return;
    }
    
    JSONRequest* request = [[JSONRequest alloc] init];

    if ([_order[@"status"] intValue] == OrderStatusWillDelivery) {
        request.URLString = _JSON_URL_ORDER_CONDIGNMENT;
    }
    else if ([_order[@"status"] intValue] == OrderStatusWaitingForConfirm) {
        request.URLString = _JSON_URL_ORDER_RECEIPT;
    }
    else if ([_order[@"status"] intValue] == 11) {
        if (buttonIndex == 0) {
            request.URLString = _JSON_URL_ORDER_REFUND_CANCEL;
        }
        else if (buttonIndex == 1) {
            request.URLString = _JSON_URL_ORDER_REFUND_CONFIRM;
        }
    }
    else if ([_order[@"status"] intValue] == 13) {
        if (buttonIndex == 0) {
            request.URLString = _JSON_URL_ORDER_RETURN_CANCEL;
        }
        else if (buttonIndex == 1) {
            request.URLString = _JSON_URL_ORDER_RETURN_CONFIRM;
        }
    }

    request.delegate = (id)self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    [request setSuccessSelector:@selector(requestSuccessSelector:)];
    [request setValue:_order[@"id"] forParameter:@"productOrderId"];
    [request asynchronous];
}


#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    if (jmf.status == JMStatusSucceed) {

        _order = jmf.data;
        _rowsTitleSource = [[NSMutableArray alloc] init];
        _rowsDataSource = [[NSMutableArray alloc] init];

        if ([jmf integerValue:@"deliveryMode"] == 0 || [jmf integerValue:@"deliveryMode"] == 2) {

            [_rowsTitleSource addObject:_L(@"title_orderitem_01")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_02")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_03")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_17")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_04")];
            if ([jmf integerValue:@"deliveryMode"] == 1) {
                [_rowsTitleSource addObject:_L(@"title_orderitem_21")];
                [_rowsTitleSource addObject:_L(@"title_orderitem_22")];
            }
            [_rowsTitleSource addObject:_L(@"title_orderitem_23")];
            [_rowsTitleSource addObject:@""];
            [_rowsTitleSource addObject:_L(@"title_orderitem_07")];
            if ([jmf stringValue:@"logisticsCompany"].length > 0) {
                [_rowsTitleSource addObject:_L(@"title_orderitem_18")];
            }
            if ([jmf stringValue:@"logisticsNumber"].length > 0) {
                [_rowsTitleSource addObject:_L(@"title_orderitem_19")];
            }
            [_rowsTitleSource addObject:_L(@"title_orderitem_08")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_09")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_10")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_11")];
        }
        else {

            [_rowsTitleSource addObject:_L(@"title_orderitem_01")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_02")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_03")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_17")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_04")];
            if ([jmf integerValue:@"deliveryMode"] == 1) {
                [_rowsTitleSource addObject:_L(@"title_orderitem_21")];
                [_rowsTitleSource addObject:_L(@"title_orderitem_22")];
            }
            [_rowsTitleSource addObject:_L(@"title_orderitem_23")];
            [_rowsTitleSource addObject:@""];
            [_rowsTitleSource addObject:_L(@"title_orderitem_07")];
            if ([jmf stringValue:@"logisticsCompany"].length > 0) {
                [_rowsTitleSource addObject:_L(@"title_orderitem_18")];
            }
            if ([jmf stringValue:@"logisticsNumber"].length > 0) {
                [_rowsTitleSource addObject:_L(@"title_orderitem_19")];
            }
            [_rowsTitleSource addObject:_L(@"title_orderitem_12")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_13")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_10")];
            [_rowsTitleSource addObject:_L(@"title_orderitem_11")];
        }

        //付款时间 -0
        if ([jmf integerValue:@"status"] == OrderStatusWaitingForPay) {
            [_rowsDataSource addObject:[jmf stringValue:@"createTime"]];
        }
        else if ([jmf integerValue:@"status"] == 1 || [jmf integerValue:@"status"] == 12) {
            [_rowsDataSource addObject:[jmf stringValue:@"paymentTime"]];
            [_rowsTitleSource replaceObjectAtIndex:0 withObject:_L(@"title_orderitem_01")];    //购买时间
        }
        else if ([jmf integerValue:@"status"] == 2 || [jmf integerValue:@"status"] == 14) {
            [_rowsDataSource addObject:[jmf stringValue:@"deliveryTime"]];
            [_rowsTitleSource replaceObjectAtIndex:0 withObject:_L(@"title_orderitem_14")];    //发货时间
        }
        else if ([jmf integerValue:@"status"] == 3) {
            [_rowsDataSource addObject:[jmf stringValue:@"receiveTime"]];
            [_rowsTitleSource replaceObjectAtIndex:0 withObject:_L(@"title_orderitem_15")];    //收货时间
        }
        else if ([jmf integerValue:@"status"] == 4) {
            [_rowsDataSource addObject:[jmf stringValue:@"evaluateTime"]];
            [_rowsTitleSource replaceObjectAtIndex:0 withObject:_L(@"title_orderitem_20")];    //收货时间
        }
        else if ([jmf integerValue:@"status"] == 11) {
            [_rowsDataSource addObject:[jmf stringValue:@"applyRefundTime"]];
            [_rowsTitleSource replaceObjectAtIndex:0 withObject:_L(@"title_orderitem_16")];    //申请时间
        }
        else if ([jmf integerValue:@"status"] == 13) {
            [_rowsDataSource addObject:[jmf stringValue:@"applyReturnTime"]];
            [_rowsTitleSource replaceObjectAtIndex:0 withObject:_L(@"title_orderitem_16")];    //申请时间
        }
        else if ([jmf integerValue:@"status"] == 10) {
            self.title = _L(@"title_order_01");     //订单详情
            UIView *blankView = [Helper blankViewWithStauts:_L(@"title_80")];
            [self.view addSubview:blankView];
            return;
        }
        
        
        //订单号 -1
        [_rowsDataSource addObject:[jmf stringValue:@"orderNumber"]];
        
        //商品名称 -2
        [_rowsDataSource addObject:[jmf idValue:@"product"][@"name"]];
        
        //交易数量
        [_rowsDataSource addObject:[NSString stringWithFormat:@"%i%@", [jmf integerValue:@"quantity"], [jmf idValue:@"product"][@"unitName"]]];

        //交易(商品)金额
        [_rowsDataSource addObject:[NSString stringWithFormat:@"%.2f", [[jmf numberValue:@"amount"] floatValue]]];
        
        //物流信息
        if ([jmf integerValue:@"deliveryMode"] == 1) {
            
            [_rowsDataSource addObject:[jmf stringValue:@"logisticsRoutes"]];
            
            if ([jmf integerValue:@"freightAmount"] == 0) {
                [_rowsDataSource addObject:_L(@"title_91")];
            }
            else {
                [_rowsDataSource addObject:[NSString stringWithFormat:@"%.2f", [((NSNumber *)[jmf objectValue:@"freightAmount"]) floatValue]]];
            }
        }
        

        //订单金额
        [_rowsDataSource addObject:[NSString stringWithFormat:@"%.2f", [((NSNumber *)[jmf objectValue:@"totalAmount"]) floatValue]]];
        
        //卖家/买家
        if ([jmf integerValue:@"sellerId"] != [_ACCOUNT_ID integerValue]) {
            
            [_rowsDataSource addObject:[jmf stringValue:@"sellerRealName"]];
            
            if ([jmf integerValue:@"deliveryMode"] == 0) {
                [_rowsTitleSource replaceObjectAtIndex:6 withObject:_L(@"title_orderitem_05")];    //卖家
            }
            else {
                [_rowsTitleSource replaceObjectAtIndex:8 withObject:_L(@"title_orderitem_05")];    //卖家
            }
        }
        else {
            [_rowsDataSource addObject:[jmf stringValue:@"buyerRealName"]];
            if ([jmf integerValue:@"deliveryMode"] == 0) {
                [_rowsTitleSource replaceObjectAtIndex:6 withObject:_L(@"title_orderitem_06")];    //买家
            }
            else {
                [_rowsTitleSource replaceObjectAtIndex:8 withObject:_L(@"title_orderitem_06")];    //买家
            }
        }
        
        //配送方式
        [_rowsDataSource addObject: ([jmf integerValue:@"deliveryMode"] == 1 ? _L(@"title_method_03") : _L(@"title_method_02")) ];   // @"快递" : @"自取"
        
        //物流公司
        if ([jmf stringValue:@"logisticsCompany"].length > 0) {
            [_rowsDataSource addObject:[jmf stringValue:@"logisticsCompany"]];
        }
        
        //单号
        if ([jmf stringValue:@"logisticsNumber"].length > 0) {
            [_rowsDataSource addObject:[jmf stringValue:@"logisticsNumber"]];
        }
        
        //收货/联系人姓名
        [_rowsDataSource addObject:[jmf stringValue:@"contactName"]];
        
        //收货地址
        [_rowsDataSource addObject:[jmf stringValue:@"contactAddress"]];
        
        //收货/联系人电话
        [_rowsDataSource addObject:[jmf stringValue:@"contactMobile"]];

        //补充说明
        [_rowsDataSource addObject:[jmf stringValue:@"remark"]];


        
        //退货/退款原因
        _reasonMessage = [NSString stringWithFormat:@"%@%@", [jmf stringValue:@"returnReason"], [jmf stringValue:@"refundReason"]];
        
        //前面整理好了数据后，重新刷新_tableView
        [_tableView reloadData];
        //数据刷新后会引起_tableView高度变化
        _tableView.frame = CGRectMake(0.0f, 0.0f, _SYS_FRAME_WIDTH, _totalHeight);
        //同时可能覆盖按钮或按钮位置不正常因此要重新计算scrollView.contentSize
        ((UIScrollView *)self.view).contentSize = CGSizeMake(320, _totalHeight + 50);
        //并重新定义按钮的位置
        _button.frame = CGRectMake(_button.frame.origin.x, _totalHeight + 5, _button.frame.size.width, _button.frame.size.height);


        //按钮、导航栏文字，及停售商品状态检查
        switch ([[_order valueForKey:@"status"] integerValue]) {
                
            case 12:
            case 0: {
                self.title = _L(@"vc_title_013");    //待付款订单详情
                if ([jmf integerValue:@"buyerId"] == [_ACCOUNT_ID integerValue] && [jmf integerValue:@"productStatus"] == 0) {
                    [_button setTitle:_L(@"btn_confirm_09") forState:UIControlStateNormal];   //确认付款
                    _button.hidden = false;
                }

                if ([jmf integerValue:@"productStatus"] != 0) {
                    [Helper showAlertWithTitle:nil andMessage:_L(@"alert_09")];   //该商品已停售
                }
            }
                break;
                
            case 1: {
                self.title = _L(@"vc_title_014");    //待发货订单详情
                if ([jmf integerValue:@"buyerId"] != [_ACCOUNT_ID integerValue]) {
                    [_button setTitle:_L(@"btn_confirm_02") forState:UIControlStateNormal];   //确认发货
                    _button.hidden = false;
                }
            }
                break;
                
            case 14:
            case 2: {
                self.title = _L(@"vc_title_015");     //待收货订单详情
                if ([jmf integerValue:@"buyerId"] == [_ACCOUNT_ID integerValue]) {
                    [_button setTitle:_L(@"btn_confirm_03") forState:UIControlStateNormal];      //确认收货
                    _button.hidden = false;
                }
            }
                break;
                
            case 3: {
                self.title = _L(@"vc_title_091");     //待评论订单详情
                if ([jmf integerValue:@"buyerId"] == [_ACCOUNT_ID integerValue]) {
                    [_button setTitle:_L(@"btn_confirm_04") forState:UIControlStateNormal];     //去评论
                    _button.hidden = false;
                }
            }
                break;
                
            case 4: {
                self.title = _L(@"vc_title_067");     //已评论订单详情
                if ([jmf integerValue:@"buyerId"] == [_ACCOUNT_ID integerValue]) {
                    [_button setTitle:_L(@"btn_confirm_04") forState:UIControlStateNormal];     //去评论
                    _button.hidden = true;
                }
            }
                break;
                
            case 11: {
                self.title = _L(@"vc_title_017");     //待退款订单
                if ([jmf integerValue:@"buyerId"] != [_ACCOUNT_ID integerValue]) {
                    [_button setTitle:_L(@"btn_confirm_05") forState:UIControlStateNormal];   //查看申请
                    _button.hidden = false;
                }
            }
                break;
                
            case 13: {
                self.title = _L(@"vc_title_018");     //待退货订单
                if ([jmf integerValue:@"buyerId"] != [_ACCOUNT_ID integerValue]) {
                    [_button setTitle:_L(@"btn_confirm_05") forState:UIControlStateNormal];   //查看申请
                    _button.hidden = false;
                }
            }
                break;
        }

    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

- (void)requestSuccessSelector:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        //如果是待收货的订单
        if ([_order[@"status"] intValue] == 2) {
            
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_139") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_confirm_04"), nil];
            alertView.tag = 901;
            [alertView show];
        }
        else {
            [self backButtonEvent];
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}


- (void)closeViewController
{
    [self backButtonEvent];
}


@end
